package com.excel.config;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.excel.ColumnInfoBean;
import com.excel.MyTable;
import com.excel.exception.DBExcelException;
import com.excel.exception.ResultSetNullException;


/**
 * 通过ResultSet取得表的配置信息
 * 
 * @author mike
 * 
 */
public class RsTableConfig extends TableConfig {
    /**
     * 用于取得表配置信息的结果集，不对其进行游标操作。
     */
    private ResultSet rs;
    private static TableConfigIFace tableConfig = null;

    private RsTableConfig(ResultSet rs) {
	this.rs = rs;
    }

    public static TableConfigIFace getTableIndtance(ResultSet rs) {
	if (tableConfig == null) {
	    tableConfig = new RsTableConfig(rs);
	}
	return tableConfig;

    }

    /**
     * 取得表配置信息
     * @throws DBExcelException 
     * @throws ResultSetNullException 
     * 
     * @throws SQLException
     */
    public MyTable getTable() throws DBExcelException, ResultSetNullException {
	// 1.0
	if (this.rs == null) {
	    throw new ResultSetNullException("结果集为空：" + this.rs);
	}
	// 1.1
	ResultSetMetaData rsmd = null;
	try {
	    rsmd = rs.getMetaData();
	} catch (SQLException e) {
	    throw new DBExcelException(""+e);
	}
	//1.2
	List<ColumnInfoBean> columns = null;
	columns = getColumnInfoesInTable();
	MyTable myTable = new MyTable();
	myTable.setTableName(this.tableName);
	myTable.setColumns(columns);
	return myTable;
    }

    public List<ColumnInfoBean> getColumnInfoesInTable() {
	List<ColumnInfoBean> retval = new ArrayList<ColumnInfoBean>();
	ResultSetMetaData rsmd = null;
	try {
	    rsmd = rs.getMetaData();
	} catch (SQLException e) {
	    // TODO
	}
	try {

	    int numColumns = rsmd.getColumnCount();

	    // Get the column names; column indices start from 1
	    for (int i = 1; i < numColumns + 1; i++) {
		ColumnInfoBean columnInfoBean = new ColumnInfoBean();

		// 字段名
		columnInfoBean.setName(rsmd.getColumnName(i));

		// 字段类型
		columnInfoBean.setTypeName(rsmd.getColumnTypeName(i));

		// 字段类型对应的java类名
		columnInfoBean.setClassName(rsmd.getColumnClassName(i));

		// 显示的长度
		columnInfoBean.setDisplaySize(String.valueOf(rsmd
			.getColumnDisplaySize(i)));

		// Precision
		columnInfoBean.setPrecision(String
			.valueOf(rsmd.getPrecision(i)));
		// Scale
		columnInfoBean.setScale(String.valueOf(rsmd.getScale(i)));
		retval.add(columnInfoBean);
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	}

	return retval;
    }


}
